package com.jason.demo.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author 大雄
 * @version 1.0
 * @description
 * @date 2022/4/4 11:18
 */
public class ProxyExample {
    static interface Car {
        void running();
    }

    static class Bus implements Car {
        @Override
        public void running() {
            System.out.println("the bus is ruunig");
        }
    }

    static class Taxi implements Car {
        @Override
        public void running() {
            System.out.println("the taxi is ruunig");
        }
    }

    /**
     * JDK proxy
     */
    static class JDKProxy implements InvocationHandler {
        // 代理对象
        private Object target;

        // 获取到代理对象
        public Object getInstance(Object target) {
            this.target = target;
            return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                    target.getClass().getInterfaces(), this);
        }

        /**
         * 执行代理方法
         *
         * @param proxy  代理对象
         * @param method 代理方法
         * @param args   方法的参数
         * @return 无
         * @throws Throwable InvocationTargetException
         */
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("动态代理前的业务处理");
            return method.invoke(target, args);
        }
    }

    public static void main(String[] args) {
        JDKProxy jdkProxy = new JDKProxy();
        Car carInstance = (Car) jdkProxy.getInstance(new Taxi());
        carInstance.running();
    }

}
